$(main);

var ANIM_DURATION = 230;
var MAIN_TITLE = 'n3musicbox';

var URL_INIT = 'init';
var URL_PLAYLIST = 'playlist';
var URL_CREATE_PLAYLIST = 'create-playlist';
var URL_LSDIR = 'ls';
var URL_ENQUEUE_PLAYLIST = 'enqueue-playlist';
var URL_LIST_QUEUE = 'list-queue';
var URL_NEXT_MUSIC = 'next-music';
var URL_PREVIOUS_MUSIC = 'previous-music';
var URL_UPDATE = 'update';
var URL_TOGGLE_PLAYING = 'toggle-playing';
var URL_GET_PROPERTIES = 'get-properties';
var URL_CREATE_DIRECTORY = 'create-directory';
var URL_LIST_PLAYLIST = 'list-playlist';
var URL_UPLOAD_MUSIC = 'upload-music';
var URL_SYNCHRONIZE_PLAYLIST = 'synchronize-playlist';
var URL_REMOVE_MUSIC = 'remove-music';
var URL_REMOVE_PLAYLIST = 'remove-playlist';
var URL_CLEAR_QUEUE = 'clear-queue';

var systemProperties = {};

var playlistXmlDom = null;

var updateThreadId;

function main(){

    $(".jq-button").button();
    changeSubtitle("console");
    $.ajax({
        url : URL_INIT,
        async : false,
        cache : false
    });

    $.ajax({
        url : URL_GET_PROPERTIES,
        dataType : "xml",
        async : true,
        cache : false,
        success : function (data, status, xhr) {
            var props = data.getElementsByTagName("property");
            for (var i = 0; i < props.length; i++) {
                var prop = props.item(i);
                systemProperties[prop.getAttribute("key")] = prop.getAttribute("value");
            }
            initProperties(systemProperties);
        }
    });

    $(".n3mb-back-to-main-console").click(function(ev) {
        $(".n3mb-shadow-content:not(:hidden)").fadeOut(ANIM_DURATION, function() {
            changeSubtitle("console");
            $("#n3mb-main-console").fadeIn(ANIM_DURATION, function() {});
        });
        return false;
    });

    $("#n3mb-toggle-playing-button").click(function (ev) {
        $.ajax({
            url : URL_TOGGLE_PLAYING,
            dataType : "xml",
            async : true,
            cache : false,
            success : function (data, status, xhr) {
                update();
            }
        });
        return false;
    });

    $("#n3mb-previous-button").click(function(ev) {
        $.ajax({
            url : URL_PREVIOUS_MUSIC,
            dataType : "xml",
            async : true,
            cache : false,
            success : function (data, status, xhr) {
                update();
                var result = data.getElementsByTagName("result").item(0).getAttribute("value");
                result = result == "true";
                if (result) {
                    $().toastmessage('showSuccessToast', 'play previous');
                } else {
                    $().toastmessage('showWarningToast', 'has no more previous');
                }
            }
        });
        return false;
    });

    $("#n3mb-next-button").click(function(ev) {
        $.ajax({
            url : URL_NEXT_MUSIC,
            dataType : "xml",
            async : true,
            cache : false,
            success : function (data, status, xhr) {
                update();
                var result = data.getElementsByTagName("result").item(0).getAttribute("value");
                result = result == "true";
                if (result) {
                    $().toastmessage('showSuccessToast', 'play next');
                } else {
                    $().toastmessage('showWarningToast', 'has no more music. rewind queue.');
                }
            }
        });
        return false;
    });
    
    $("#n3mb-clear-queue-button").click(function (ev) {
        $.ajax({
            url : URL_CLEAR_QUEUE,
            dataType : "xml",
            async : true,
            cache : false,
            success : function (data, status, xhr) {
                update();
                var result = data.getElementsByTagName("result").item(0).getAttribute("value");
                result = result == "true";
                if (result) {
                    $().toastmessage('showSuccessToast', 'queue has been cleared.');
                } else {
                    $().toastmessage('showToast', {
                        text     : 'failed to clear queue.',
                        sticky   : true,
                        type     : 'error'
                    });
                }
            }
        });
        return false;
    });

    $("#n3mb-playlist-button").click(function(ev) {
        $("#n3mb-main-console").fadeOut(ANIM_DURATION, function() {
            changeSubtitle("playlist");
            $("#n3mb-playlist").fadeIn(ANIM_DURATION, function() {
                showPlaylist();
            });
        });
        return false;
    });

    $("#n3mb-playlist-create-button").click(function(ev) {
        $("#n3mb-playlist-create-dialog").dialog({
            title : "create playlist",
            width : 600,
            modal : true,
            buttons : [
                {
                    text : "cancel",
                    click : function() {
                        $(this).dialog("close");
                    }
                },
                {
                    text : "create",
                    click : function() {
                        $.ajax({
                            type        :'GET',
                            url         : URL_CREATE_PLAYLIST,
                            async       : false,
                            cache : false,
                            dataType    : 'xml',
                            data        : {
                                name   : $("#n3mb-playlist-select-name-input").val(),
                                method : $("input[name=n3mb-playlist-create-method]").val(),
                                sourceDirectory : $("#n3mb-playlist-select-directory-input").val()
                            },
                            success     : function (data, status, xhr) {
                                var resultElem = data.getElementsByTagName("result").item(0);
                                var result  = resultElem.getAttribute("value");
                                result = result == "true";
                                if (!result) {
                                    $("#n3mb-util-dialog")
                                    .html("<p>failed to create playlist.</p>")
                                    .dialog({
                                        title : "error",
                                        width : 400,
                                        modal : true,
                                        buttons : [
                                            {
                                                text : "ok",
                                                click : function() {
                                                    $(this).dialog("close");
                                                }
                                            }
                                        ]
                                    });
                                } else {
                                    $("#n3mb-playlist-create-dialog").dialog("close");
                                    showPlaylist();
                                    $("#n3mb-playlist-select-name-input").val("");
                                    $("#n3mb-playlist-select-directory-input").val(systemProperties["user.home"]);
                                }
                            }
                        });
                    }
                }
            ]
        });
        return false;
    });

    $("#n3mb-playlist-select-directory-chooser-button").click(function(ev) {
        showPlaylistDirectoryChooserDialog($("#n3mb-playlist-select-directory-input").val());
        $("#n3mb-playlist-select-directory-chooser-dialog").dialog({
            title : "choose directory",
            width : 800,
            height: 600,
            modal : true,
            buttons : [
                {
                    text : "cancel",
                    click : function() {
                        $(this).dialog("close");
                    }
                },
                {
                    text : "select",
                    click : function() {
                        var path = $("#n3mb-playlist-select-directory-chooser-path").val();
                        $("#n3mb-playlist-select-directory-input").val(path);
                        if (!$("#n3mb-playlist-select-name-input").val()) {
                            var fileBaseNameRegexpString = "\\" + systemProperties["file.separator"] + "([^\\" + systemProperties["file.separator"] + "]+)$";
                            var fileBaseNameRegexp = new RegExp(fileBaseNameRegexpString);
                            var n = path.match(fileBaseNameRegexp);
                            var defaultPlaylistName = n.length > 1 ? n[1] : "";
                            $("#n3mb-playlist-select-name-input").val(defaultPlaylistName);
                        }
                        $(this).dialog("close");
                    }
                }
            ],
            resize : function (ev, ui) {
                /*
                var dy = ui.size.height - ui.originalSize.height;
                var orginalContentHeight = $("#n3mb-playlist-select-directory-chooser-content").height();
                var contentHeight = orginalContentHeight + dy;
                $("#n3mb-playlist-select-directory-chooser-content").height(contentHeight);
                //*/
            }
        });
    });

    $("#n3mb-create-directory-button").click(function (ev) {
        updateNewDirectoryPathPreview();
        $("#n3mb-create-directory-dialog").dialog({
            title : "create directory",
            width : 560,
            height: 200,
            modal : true,
            buttons : [
                {
                    text : "cancel",
                    click : function() {
                        $(this).dialog("close");
                    }
                },
                {
                    text : "create",
                    click : function() {
                        var thisDialog = $(this);
                        var path = 
                                $("#n3mb-playlist-select-directory-chooser-path").val() + 
                                systemProperties["file.separator"] + 
                                $("#n3mb-create-directory-input").val();
                        $.ajax({
                            type        :'GET',
                            url         : URL_CREATE_DIRECTORY,
                            data : {
                                'path' : path
                            },
                            cache       : false,
                            async       : false,
                            dataType    : 'xml',
                            success     : function (data, status, xhr) {
                                var result = data.getElementsByTagName("result").item(0).getAttribute("value");
                                result = result == "true";
                                if (result) {
                                    $().toastmessage('showSuccessToast', 'directory was created.');
                                    thisDialog.dialog("close");
                                    $("#n3mb-create-directory-input").val("NewPlaylist");
                                    showPlaylistDirectoryChooserDialog();
                                } else {

                                    $("#n3mb-util-dialog")
                                    .html("<p>failed to create directory.</p>")
                                    .dialog({
                                        title : "error",
                                        width : 600,
                                        modal : true,
                                        buttons : [
                                            {
                                                text : "ok",
                                                click : function() {
                                                    $(this).dialog("close");
                                                }
                                            }
                                        ]
                                    });
                                }
                            }
                        });
                    }
                }
            ]
        });
    });

    $("#n3mb-create-directory-input").keypress(updateNewDirectoryPathPreview);
    $("#n3mb-create-directory-input").keyup(updateNewDirectoryPathPreview);

    updateThreadId = setInterval(function() {
        update();
    }, 500);
}

function update() {
    $.ajax({
        type        :'GET',
        url         : URL_UPDATE,
        cache       : false,
        async       : true,
        dataType    : 'xml',
        success     : function (data, status, xhr) {
            var running = data.getElementsByTagName("player").item(0).getAttribute("running") == "true";
            if (running) {
                $("#n3mb-toggle-playing-button-image").attr("src", "images/player_pause.png");
                $("#n3mb-toggle-playing-button-legend").html("pause");
            } else {
                $("#n3mb-toggle-playing-button-image").attr("src", "images/player_start.png");
                $("#n3mb-toggle-playing-button-legend").html("play");
            }
            $("#n3mb-queue-content").html(makeQueueHtml(data));
            initQueueHtml();
        }
    });
}

function showQueue() {
    $.ajax({
        type        :'GET',
        url         : URL_LIST_QUEUE,
        cache       : false,
        async       : false,
        dataType    : 'xml',
        success     : function (data, status, xhr) {
            $("#n3mb-queue-content").html(makeQueueHtml(data));
            initQueueHtml();
        }
    });
}

function makeQueueHtml(dom) {
    var html = '<ul style="list-style-type:none;width:100%;margin-top:30px;padding:0;">';
    var queuePosition = dom.getElementsByTagName('queue').item(0).getAttribute('position');
    var musicElems = dom.getElementsByTagName('music');
    for (var i = 0; i < musicElems.length; i++) {
        var musicElem = musicElems.item(i);
        html += 
            '<li style="font-size:23px;">' + 
                '<div style="padding:10px; " class="n3mb-queue-item ui-widget-content ' + (queuePosition == i ? "ui-state-hover" : "") + '">' + 
                    musicElem.getAttribute("name") + 
                '</div>' + 
            '</li>';
    }
    html += '</ul>';
    return html;
}

function initQueueHtml() {
    
}

function showPlaylist() {
    $.ajax({
        type        :'GET',
        url         : URL_PLAYLIST,
        cache       : false,
        dataType    : 'xml',
        success     : function (data, status, xhr) {
            playlistXmlDom = data;
            $("#n3mb-playlist-content").html(makePlaylistHtml(playlistXmlDom));
            initPlaylistHtml();
        }
    });
}

function showPlaylistDirectoryChooserDialog(targetDirectory) {
    if (targetDirectory) 
        $("#n3mb-playlist-select-directory-chooser-path").val(targetDirectory);
    targetDirectory = targetDirectory ? targetDirectory : $("#n3mb-playlist-select-directory-chooser-path").val();
    $.ajax({
        type : 'GET',
        url : URL_LSDIR,
        async : false,
        cache : false,
        dataType : 'xml',
        data : {
            'targetDirectory' : targetDirectory
        },
        success : function (data, status, xhr) {
            var result = data.getElementsByTagName("result").item(0).getAttribute("value");
            result = result == "true";
            if (!result) {
                $().toastmessage('showWarningToast', 'can not access specified directory.');
                return;
            }
            var directoryElems = data.getElementsByTagName("directory");
            var parentDirectory = data.getElementsByTagName("parentDirectory").item(0).getAttribute('path');
            var directories = [];
            for (var i = 0; i < directoryElems.length; i++) {
                directories[i] = directoryElems.item(i).getAttribute('path');
            }
            directories.sort();
            
            var html = "<ul style='padding:0;'>";
            html += "<li class='n3mb-playlist-select-directory-chooser-directory ui-widget-content' id='" + parentDirectory + "' style='padding:2px; cursor: pointer;'>.. (" + parentDirectory + ")</li>";
            for (var j = 0; j < directories.length; j++) {
                html += "<li class='n3mb-playlist-select-directory-chooser-directory ui-widget-content' id='" + directories[j] + "' style='padding:2px; cursor: pointer;'>" + directories[j] + "</li>";
            }
            html += "</ul>";
            $("#n3mb-playlist-select-directory-chooser-content").html(html);
            $(".n3mb-playlist-select-directory-chooser-directory").click(function(ev) {
                var targetDirectory = $(ev.target).attr('id');
                $("#n3mb-playlist-select-directory-chooser-path").val(targetDirectory);
                showPlaylistDirectoryChooserDialog(targetDirectory)
            })
            .mouseover(function(ev) {
                $(ev.target).addClass("ui-state-hover");
            })
            .mouseout(function (ev) {
                $(ev.target).removeClass("ui-state-hover");
            })
            .mousedown(function (ev) {
                $(ev.target).addClass("ui-state-focus");
            })
            .mouseup(function (ev) {
                $(ev.target).removeClass("ui-state-focus");
            })
        }
    });
}

function changeSubtitle(subtitle) {
    $("title").html(subtitle + " | " + MAIN_TITLE)
    $("#n3mb-subtitle").html(subtitle);
}

function makePlaylistHtml(dom) {
    var playlistElems = dom.getElementsByTagName('playlist');
    var html = '<ul style="list-style-type:none;width:100%;margin-top:30px;padding:0;">';
    for (var i = 0; i < playlistElems.length; i++) {
        var playlistElem = playlistElems.item(i);
        html += 
            '<li style="font-size:23px;">' + 
                '<div style="padding:10px;" class="n3mb-playlist-item ui-widget-content ">' + 
                    '<div style="float:left;width:17%;">' + 
                        '<button title="enqueue ' + playlistElem.getAttribute('name') + '" value="' + playlistElem.getAttribute('id') + '" class="jq-button n3mb-enqueue-playlist"><span class="ui-icon ui-icon-play"></span></button>' + 
                        '<button title="open ' + playlistElem.getAttribute('name') + '" value="' + playlistElem.getAttribute('id') + '" class="jq-button n3mb-open-playlist"><span class="ui-icon ui-icon-folder-open"></span></button>' + 
                    '</div>' +
                    '<div style="float:left;width:74%;">' + playlistElem.getAttribute('name') + '</div>' +
                    '<div style="float:right;width:8%;">' + 
                        '<button title="remove ' + playlistElem.getAttribute('name') + '" value="' + playlistElem.getAttribute('id') + '" class="jq-button n3mb-remove-playlist"><span class="ui-icon ui-icon-trash"></span></button>' + 
                    '</div>' + 
                    '<div style="clear:both;"></div>' + 
                '</div>' + 
            '</li>';
    }
    html += '</ul>';
    return html;
}

function initPlaylistHtml() {
    $(".jq-button").button();

    $(".n3mb-enqueue-playlist").click(function (ev) {
        var playlistId = $(this).val();
        enqueuePlaylist(playlistId);
        return false;
    });
    
    $(".n3mb-open-playlist").click(function (ev) {
        openPlaylistDialog($(this).val());
        return false;
    });
    
    $(".n3mb-remove-playlist").click(function (ev) {
        var playlistId = $(this).val();
        var confirmHtml = "remove playlist.";
        $("n3mb-playlist-dialog-remove-playlist-confirm-dialog-message").html(confirmHtml);
        $("#n3mb-playlist-dialog-remove-playlist-confirm-dialog").dialog({
            title : "remove playlist.",
            width : 400,
            height: 200,
            modal : true,
            buttons : [
                {
                    text : "cancel",
                    click : function() {
                        $(this).dialog("close");
                    }
                },
                {
                    text : "ok",
                    click : function() {
                        var removeDirectory = $("#n3mb-playlist-dialog-remove-playlist-confirm-dialog-remove-with-directory").is(":checked");
                        $.ajax({
                            type : "GET",
                            url : URL_REMOVE_PLAYLIST,
                            data : {
                                playlistId : playlistId,
                                removeDirectory : removeDirectory
                            },
                            cache : false,
                            async: true,
                            dataType : "xml",
                            success : function (data, status, xhr) {
                                var result = data.getElementsByTagName("result").item(0).getAttribute("value");
                                result = result == "true";
                                var playlistName = data.getElementsByTagName("playlist").item(0).getAttribute("name");
                                if (result) {
                                    $().toastmessage('showSuccessToast', playlistName + ' has been removed.');
                                    $("#n3mb-playlist-dialog-remove-playlist-confirm-dialog").dialog("close");
                                    $("#n3mb-playlist-dialog-" + playlistId) && $("#n3mb-playlist-dialog-" + playlistId).dialog("close").remove();
                                    showPlaylist();
                                } else {
                                    $("#n3mb-util-dialog")
                                    .html("<p>failed to remove " + playlistName + ".</p>")
                                    .dialog({
                                        title : "error",
                                        width : 400,
                                        height: 200,
                                        modal : true,
                                        buttons : [
                                            {
                                                text : "ok",
                                                click : function() {
                                                    $(this).dialog("close");
                                                }
                                            }
                                        ]
                                    });
                                }
                                
                                $("#n3mb-playlist-dialog-remove-playlist-confirm-dialog-remove-with-directory").attr("checked", false);
                            }
                        });
                    }
                }
            ]
        });
        
        return false;
    });
}

function openPlaylistDialog(playlistId) {
    $.ajax({
        type : "GET",
        url : URL_LIST_PLAYLIST,
        data : {playlistId : playlistId},
        async: true,
        cache : false,
        dataType : "xml",
        success : function (data, status, xhr) {
            var playlistDialogId = "n3mb-playlist-dialog-" + playlistId;
            var playlistName = data.getElementsByTagName("playlist").item(0).getAttribute("name");
            if ($("#" + playlistDialogId).length == 1) {
                $("#" + playlistDialogId).html(makePlaylistDialogHtml(data));
            } else {
                var playlistDialog = $("<div id='" + playlistDialogId + "' class='' style='display: none;'>" + makePlaylistDialogHtml(data) + "</div>");
                $("#n3mb-playlist-dialog-workspace").append(playlistDialog);
            }
            $("#" + playlistDialogId).ready(function () {
                $("#" + playlistDialogId).dialog({
                    title : playlistName,
                    width : 600,
                    height: 400,
                    modal : false
                }).dialog("moveToTop");
                initPlaylistDialogHtml(playlistId, playlistName);
            });
        }
    });
}

function makePlaylistDialogHtml(dom) {
    var playlistElem = dom.getElementsByTagName("playlist").item(0);
    var playlistName = playlistElem.getAttribute("name");
    var playlistId = playlistElem.getAttribute("id");
    var musicElems = playlistElem.getElementsByTagName("music");
    var musicListHtml = "";
    for (var i = 0; i < musicElems.length; i++) {
        var musicElem = musicElems.item(i);
        var musicCheckBoxName = playlistId + "-music-checkbox";
        var musicCheckBoxId = playlistId + "-" + musicElem.getAttribute("order");
        musicListHtml += 
            "<li>" + 
                "<input type='checkbox' name='" + musicCheckBoxName + "' id='" + musicCheckBoxId + "' value='" + musicElem.getAttribute("order") + "' title='" + musicElem.getAttribute("url") + "' />" +
                "<label style='cursor:pointer;' for='" + musicCheckBoxId + "'>" + musicElem.getAttribute("name") + "</label>" +
            "</li>";
    }
    
    if (musicElems.length == 0) {
        musicListHtml += "<li>" + playlistName + " is empty.</li>";
    }
    
    var html =  
                "<div>" + 
                    "<div>" + 
                        "<button value='" + playlistId + "' style='vertical-align: middle;' class='jq-button' id='n3mb-playlist-dialog-enqueue-button-" + playlistId + "' title='enqueue this playlist'><span class='ui-icon ui-icon-circle-triangle-e'></span></button>" + 
                        "<button value='" + playlistId + "' style='vertical-align: middle;' class='jq-button' id='n3mb-playlist-dialog-fileupload-button-" + playlistId + "' title='upload music to this playlist'><span class='ui-icon ui-icon-circle-arrow-n'></span></button>" + 
                        "<button value='" + playlistId + "' style='vertical-align: middle;' class='jq-button' id='n3mb-playlist-dialog-synchronize-button-" + playlistId + "' title='synchronize this playlist to directory'><span class='ui-icon ui-icon-transferthick-e-w'></span></button>" + 
                        "<button value='" + playlistId + "' style='vertical-align: middle;' class='jq-button' id='n3mb-playlist-dialog-remove-music-button-" + playlistId + "' title='remove selected music'><span class='ui-icon ui-icon-trash'></span></button>" + 
                    "</div>" + 
                    "<div>" + 
                        "<ul style='list-style-type:none;padding:0;'>" + 
                            musicListHtml + 
                        "</ul>" + 
                    "</div>" + 
                "</div>";
    
    return html;
}

function initPlaylistDialogHtml(playlistId, playlistName) {
    var musicCheckBoxName = playlistId + "-music-checkbox";
    
    $(".jq-button").button();
    
    $("#n3mb-playlist-dialog-enqueue-button-" + playlistId).click(function (ev) {
        enqueuePlaylist(playlistId);
    });
    
    $("#n3mb-playlist-dialog-fileupload-button-" + playlistId).click(function (ev) {
        showFileuploadDialog(playlistId, playlistName, function (res) {
            var result = res.getElementsByTagName("result").item(0).getAttribute("value");
            result = result == "true";
            if (result) {
                $("#n3mb-fileupload-dialog").dialog("close");
                openPlaylistDialog(playlistId);
                $().toastmessage('showSuccessToast', 'uploading is successfully finished.');
                initFileuploadDialogFormFields();
            } else {
                $().toastmessage('showToast', {
                    text     : 'failed to upload music to ' + playlistName + '.',
                    sticky   : true,
                    type     : 'error'
                });
            }
        });
        return false;
    });
    
    $("#n3mb-playlist-dialog-synchronize-button-" + playlistId).click(function (ev) {
        $.ajax({
            type : "GET",
            url : URL_SYNCHRONIZE_PLAYLIST,
            data : {playlistId : playlistId},
            async: true,
            cache : false,
            dataType : "xml",
            success : function (data, status, xhr) {
                var result = data.getElementsByTagName("result").item(0).getAttribute("value");
                result = result == "true";
                if (result) {
                    openPlaylistDialog(playlistId);
                    $().toastmessage('showSuccessToast', playlistName + ' has been synchronized to its directory.');
                } else {
                    $().toastmessage('showToast', {
                        text     : 'failed to synchronize ' + playlistName + ' to directory.',
                        sticky   : true,
                        type     : 'error'
                    });
                }
            }
        });
    });
    
    $("#n3mb-playlist-dialog-remove-music-button-" + playlistId).click(function (ev) {
        var checkedMusics = $("input[name='" + musicCheckBoxName + "']:checked");
        if (checkedMusics.length == 0) {
            $().toastmessage('showWarningToast', 'specify music files to delete.');
            return;
        }
        
        var targetMusicHtml = "<ul>";
        var targetMusicListHtml = "";
        $.each(checkedMusics, function (index, musicElem) {
            var music = $(musicElem);
            var musicUrl = music.attr("title");
            targetMusicListHtml += "<li>" + musicUrl + "</li>";
        });
        
        targetMusicHtml = 
            "<ul>" + 
                targetMusicListHtml + 
            "</ul>";
        
        $("#n3mb-playlist-dialog-remove-music-confirm-dialog-target-music-files").html(targetMusicHtml);
        $("#n3mb-playlist-dialog-remove-music-confirm-dialog").dialog({
            title : "remove music files confirmation. ",
            width : 600,
            height: 400,
            modal : true,
            buttons : [
                {
                    text : "cancel",
                    click : function() {
                        $(this).dialog("close");
                    }
                },
                {
                    text : "ok",
                    click : function() {
                        var removeMusicOrders = [];
                        removeMusicOrders = checkedMusics.map(function() {
                          return $(this).val();
                        }).get();
                        
                        $.ajax({
                            type : "GET",
                            url : URL_REMOVE_MUSIC,
                            data : {
                                playlistId : playlistId,
                                orders : removeMusicOrders
                            },
                            async: true,
                            cache : false,
                            dataType : "xml",
                            success : function (data, status, xhr) {
                                var result = data.getElementsByTagName("result").item(0).getAttribute("value");
                                result = result == "true";
                                if (result) {
                                    $("#n3mb-playlist-dialog-remove-music-confirm-dialog").dialog("close");
                                    openPlaylistDialog(playlistId);
                                    $().toastmessage('showSuccessToast', 'specified music files has been deleted.');
                                } else {
                                    $().toastmessage('showToast', {
                                        text     : 'failed to delete music.',
                                        sticky   : true,
                                        type     : 'error'
                                    });
                                }
                            }
                        });
                    }
                }
            ]
        });
        return false;
    });
}

function showFileuploadDialog(playlistId, playlistName, postUploadCallback) {
    manipulateFileuploadDialogFormFields();
    $("#n3mb-fileupload-dialog").dialog({
        title : "upload music to " + playlistName,
        width : 500,
        height: 400,
        modal : true,
        buttons : [
            {
                text : "cancel",
                click : function() {
                    $(this).dialog("close");
                }
            },
            {
                text : "upload",
                click : function() {
                    if ($("input.n3mb-fileupload-form-file").length == 1) {
                        $().toastmessage('showWarningToast', 'select music files to upload.');
                        return;
                    }
                    $("#n3mb-fileupload-form-hidden-playlist-id").val(playlistId);
                    $('#n3mb-fileupload-form-fields')
                        .upload(URL_UPLOAD_MUSIC, postUploadCallback, 'xml');
                }
            }
        ]
    });
}

function manipulateFileuploadDialogFormFields() {
    var files = $("input.n3mb-fileupload-form-file");
    
    var _index = 0;
    var newAppendFileRemoveButtonId = "";
    if (files.length == 0) {
        $("#n3mb-fileupload-form-fields")
            .append($(
                '<input class="n3mb-fileupload-form-file" name="n3mb-fileupload-form-file-0" id="n3mb-fileupload-form-file-0" type="file" />' +
                "<button disabled='disabled' value='" + _index + "' style='vertical-align: middle;' id='n3mb-fileupload-form-file-remove-button-" + _index + "' class='jq-button n3mb-fileupload-form-file-remove-button' title='remove'><span class='ui-icon ui-icon-circle-close'></span></button>"
            ));
    } else {
        $.each(files, function (index, fileElem) {
            var file = $(fileElem);
            if (!file.val()) {
                var idElems = file.attr("id").split("-");
                var __index = idElems[idElems.length - 1];
                file.remove();
                $("#n3mb-fileupload-form-file-remove-button-" + __index).remove();
            }
        });

        $.each(files, function (index, fileElem) {
            _index = index;
            var file = $(fileElem);
            var idElems = file.attr("id").split("-");
            var __index = idElems[idElems.length - 1];
            var removeButton = $("#n3mb-fileupload-form-file-remove-button-" + __index);
            var _newAppendFileRemoveButtonId = "n3mb-fileupload-form-file-remove-button-" + index;
            removeButton.replaceWith($("<button value='" + index + "' style='vertical-align: middle;' id='" + _newAppendFileRemoveButtonId + "' class='jq-button n3mb-fileupload-form-file-remove-button' title='remove'><span class='ui-icon ui-icon-circle-close'></span></button>"));
            //removeButton.attr("id", "#n3mb-fileupload-form-file-remove-button-" + index);
            //removeButton.attr("disabled", false);
            file.attr("name", "n3mb-fileupload-form-file-" + index)
                .attr("id", "n3mb-fileupload-form-file-" + index);
            
            $("#" + _newAppendFileRemoveButtonId)
                .click(function (ev) {
                    var index = $(ev.currentTarget).val();
                    var file = $("#n3mb-fileupload-form-file-" + index);
                    var idElems = file.attr("id").split("-");
                    var ___index = idElems[idElems.length - 1];
                    file.remove();
                    $("#n3mb-fileupload-form-file-remove-button-" + ___index).remove();
                    manipulateFileuploadDialogFormFields();
                    return false;
                });
        });
        
        _index++;
        $("#n3mb-fileupload-form-fields")
            .append($(
                '<input class="n3mb-fileupload-form-file" name="n3mb-fileupload-form-file-' + _index + '" id="n3mb-fileupload-form-file-' + _index + '" type="file" />' + 
                "<button disabled='disabled' value='" + _index + "' style='vertical-align: middle;' id='n3mb-fileupload-form-file-remove-button-" + _index + "' class='jq-button n3mb-fileupload-form-file-remove-button' title='remove'><span class='ui-icon ui-icon-circle-close'></span></button>"
            ));
    }
    
    newAppendFileRemoveButtonId = "n3mb-fileupload-form-file-remove-button-" + _index;
    $(".jq-button").button();
    $("input.n3mb-fileupload-form-file:file").change(function (ev) {
        manipulateFileuploadDialogFormFields();
        return false;
    });
    $("#" + newAppendFileRemoveButtonId)
        .click(function (ev) {
            var index = $(ev.currentTarget).val();
            $("#n3mb-fileupload-form-file-" + index).remove();
            $("#" + newAppendFileRemoveButtonId).remove();
            manipulateFileuploadDialogFormFields();
            return false;
        });
}

function initFileuploadDialogFormFields() {
    $("input.n3mb-fileupload-form-file").remove();
    $(".n3mb-fileupload-form-file-remove-button").remove();
    manipulateFileuploadDialogFormFields();
}

function initProperties(systemProperties) {
    $("#n3mb-playlist-select-directory-input").val(systemProperties["user.home"]);
}

function updateNewDirectoryPathPreview() {
    var path = 
            $("#n3mb-playlist-select-directory-chooser-path").val() + 
            systemProperties["file.separator"] + 
            $("#n3mb-create-directory-input").val();
    $("#n3mb-create-directory-new-directory-preview").html(path);
    return true;
}

function enqueuePlaylist(playlistId) {
    $.ajax({
        type : "GET",
        url : URL_LIST_PLAYLIST,
        data : {playlistId : playlistId},
        async: true,
        cache : false,
        dataType : "xml",
        success : function (data, status, xhr) {
            var musicElems = data.getElementsByTagName("music");
            if (musicElems.length == 0) {
                $().toastmessage('showWarningToast', 'playlist is empty.');
            } else {
                $.ajax({
                    url : URL_ENQUEUE_PLAYLIST,
                    data : {playlistId : playlistId},
                    cache : false,
                    success : function (data, status, xhr) {
                        $().toastmessage('showSuccessToast', 'enqueue this playlist.');

                    }
                });
            }
        }
    });
    return false;
}